<template>
	<view>
		<view style="margin: 100px 30px auto 30px;">
			<uv-button @click="showVideoAd" type="success">看视频</uv-button>
		</view>

		<uv-modal ref="modal" title="继续观看" content='是否继续观看视频' confirmText="继续观看" cancelText="取消观看" @confirm="adconfirm"
			@cancel="adcancel" :showCancelButton="true"></uv-modal>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script setup>
	import {
		onMounted,
		ref
	} from 'vue';
	import {
		onShow
	} from '@dcloudio/uni-app'
	import config from '../../common/config.js';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	let interstitialAd = null;
	let isInterstitialLoading = false;
	let rewardedVideoAd = null;
	let isVideoAdLoading = false;
	let modal = ref(null)
	let toast = ref(null)

	function adconfirm() {
		showVideoAd();
	}

	function adcancel() {

	}
	
	function showToast(params) {
		toast.value.show({
			...params,
			complete() {}
		})
	}
	

	onLoad((op) => {
		console.log(op)
	})

	onShow(() => {
		//插屏广告实例
		if (wx.createInterstitialAd) {
			interstitialAd = wx.createInterstitialAd({
				adUnitId: config.InterstitialID
			})
			interstitialAd.onLoad(() => {
				console.log('插屏广告加载')
				if (interstitialAd && !isInterstitialLoading) {
					interstitialAd.show().catch((err) => {
						console.error('插屏广告显示失败', err)
					// 	if (isVideoAdLoading == true) {
					// 		showVideoAd();
					// 	}
					})
				}
			})
			interstitialAd.onError((err) => {
				console.error('插屏广告加载失败', err)
				// if (isVideoAdLoading == true) {
				// 	showVideoAd();
				// }
			})
			interstitialAd.onClose(() => {
				console.log('插屏广告关闭')
				isInterstitialLoading = true
				// if (isVideoAdLoading == true) {
				// 	showVideoAd();
				// }
			})
		}
	})

	onMounted(() => {

		//激励广告
		if (wx.createRewardedVideoAd) {
			rewardedVideoAd = wx.createRewardedVideoAd({
				adUnitId: config.RewardedVideoID
			})
			rewardedVideoAd.onLoad(() => {
				console.log('激励广告加载成功');
				isVideoAdLoading = true
				// if (isInterstitialLoading == true) {
				// 	showVideoAd();
				// }
			})
			rewardedVideoAd.onError((e) => {
				console.error('激励视频广告加载失败', e)
				showToast({
					type: 'default',
					message: e,
				})
			})
			rewardedVideoAd.onClose((e) => {
				// 用户点击了关闭广告
				console.log("激励广告关闭", e);
				modal.value.open();
				// if (e && e.isEnded) {
				// 	selectItem.ad = true;
				// 	getlink(selectItem)
				// } else {
				// 	showToast({
				// 		type: 'default',
				// 		message: '激励广告未观看完成',
				// 	})
				// }
			})
		}
	})

	function showVideoAd() {
		if (isVideoAdLoading) {
			isVideoAdLoading = false;
			rewardedVideoAd.show();
		} else {
			showToast({
				type: 'default',
				title: '激励广告未加载完成',
				message: "激励广告未加载完成",
			})
		}
	}
</script>

<style>

</style>